package com.drd.dt.back.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.drd.dt.back.dao.AtWillUpdataMapper;
import com.drd.dt.back.service.IAtWillUpdataService;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import com.drd.dt.filter.UserThreadLocal;
import com.drd.dt.modular.dao.OrderMapper;
import com.drd.dt.modular.dao.UserMapper;
import com.drd.dt.modular.dto.UserMoneyDTO;
import com.drd.dt.modular.entity.Order;
import com.drd.dt.modular.entity.User;
import com.drd.dt.modular.entity.UserMoney;
import com.drd.dt.modular.service.UserService;
import com.drd.dt.util.CodeUtils;
import com.drd.dt.util.EmojiUtil;
import com.drd.dt.util.EmojiUtil2;
import com.drd.dt.util.ResultUtil;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;


@Service
@Transactional
public class AtWillUpdataServiceImpl implements IAtWillUpdataService {

    @Autowired
    private AtWillUpdataMapper atWillUpdataMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 获取 用户的收益信息
     **/
    public Tip getUserProfit(String user_id) {
        UserMoney userMoney = atWillUpdataMapper.getUserProfile(user_id);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), userMoney);
    }

    /**
     * 修改用户收益
     **/
    public Tip updataUserProfit(UserMoney userMoney) {
        int req = atWillUpdataMapper.updataUserProfile(userMoney);
        if (req < 1) {
            return ResultUtil.result(BizExceptionEnum.SELECT_ERROR.getCode(), BizExceptionEnum.SELECT_ERROR.getMessage());
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }

    /**
     * 粉丝列表 粉丝收益 粉丝数
     */
    @Override
    public Tip getFSList(String user_id, String fs_user_id, Integer directRelation, Integer page, Integer count, String is_vip) throws Exception {
        Integer pageNum = page / count + 1;
        Page pa = new Page(pageNum, count);

        if (StringUtils.isEmpty(user_id)) {//用户是否存在
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        if (!StringUtils.isEmpty(fs_user_id)) {//某个粉丝
            Map map = new HashMap();
            map.put("user_id", user_id);
            map.put("fs_user_id", fs_user_id);
            List<UserMoneyDTO> userMoneyList = new ArrayList<>();
            UserMoneyDTO userMoneyDTO = atWillUpdataMapper.getUserZJFSProfile(map);
            if (null != userMoneyDTO) {
                userMoneyList.add(userMoneyDTO);
            }
            pa.setRecords(userMoneyList);
        } else { //查询所有 粉丝
            User user = userMapper.selectUserId(Integer.parseInt(user_id));
            if (null == user) {
                throw new BussinessException(BizExceptionEnum.OT_USER_ERROR);
            }
            String code = user.getFriend_code();//当前用户的邀请码
            Integer friend_code = CodeUtils.codeToId(code);
            List<Integer> ids = null;
            List<Integer> ids_zs = atWillUpdataMapper.getDirectFS(Integer.parseInt(user_id));//直属粉丝
            if (directRelation == 1) {
                ids = ids_zs;
            } else if (directRelation == 2) {//非直属 普通   =   所有 - 直属粉丝
                ids = atWillUpdataMapper.getIndirectFS(ids_zs, Integer.parseInt(user_id));
            } else {
                ids = atWillUpdataMapper.getAllFS(friend_code);//所有下级粉丝
            }
            //获取用户收益信息
            List<UserMoneyDTO> list = atWillUpdataMapper.selectUserZJFSProfile(pa, ids, Integer.parseInt(is_vip));
            List<UserMoneyDTO> values = atWillUpdataMapper.getFSEarningsDetail(pa, ids);
            list.forEach(item -> {
                for (UserMoneyDTO dto : values) {
                    if (item.getUser_id().equals(dto.getUser_id())) {
                        item.setAccumulativeTotalEarnings(dto.getAccumulativeTotalEarnings());
                        item.setBudgetEarnings(dto.getBudgetEarnings());
                        break;
                    }
                }
            });
            //获取用户
            pa.setRecords(list);
        }

        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), pa);
    }

    /**
     * 查询某个用户的 收益信息 以级粉丝数量
     */
    public Tip getFsDetail(String user_id) {
        Map map = atWillUpdataMapper.getFsDetail(Integer.parseInt(user_id));//收益信息
        if (null != map) {
            Map parm = new HashMap();
            parm.put("user_id", user_id);
            List<Map> reqMapList = atWillUpdataMapper.selectForm(parm);
            if (null != reqMapList && reqMapList.size() > 0) {
                map.putAll(reqMapList.get(0)); //报表信息 上月如果多个 报表默认取第一个
            }
            return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), map);
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }

    /**
     * 修改粉丝量 上月收益  累计收益
     */
    @Override
    public Tip updateFsDetail(Integer user_id, Double estimate_commission, Double estimate_bounty,
                              Double estimate_fans, Double owner_estimate, Double accumulated,
                              Double activity_accumulated, Double fans_estimate, Double bounty_accumulated,
                              Integer direct_fans, Integer indirect_fans) {
        Map map = new HashMap();
        map.put("user_id", user_id);
        map.put("estimate_commission", estimate_commission);
        map.put("estimate_bounty", estimate_bounty);
        map.put("estimate_fans", estimate_fans);
        map.put("owner_estimate", owner_estimate);
        map.put("accumulated", accumulated);
        map.put("activity_accumulated", activity_accumulated);
        map.put("fans_estimate", fans_estimate);
        map.put("bounty_accumulated", bounty_accumulated);
        map.put("direct_fans", direct_fans);
        map.put("indirect_fans", indirect_fans);
        //1 查询是否存在上月收益报表
        List<Map> reqMapList = atWillUpdataMapper.selectForm(map);
        if (null != reqMapList && reqMapList.size() > 0) {
            //1.1 修改
            Map reqMap = reqMapList.get(0);
            map.put("id", reqMap.get("id"));
            int reqUpd = atWillUpdataMapper.updateForm(map);
            if (reqUpd < 0) {
                throw new BussinessException(BizExceptionEnum.UPDATE_ERROR);
            }
        } else {
            //1.1 新增
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date); // 设置为当前时间
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月
            date = calendar.getTime();
            String create_time = format.format(date);
            map.put("create_time", create_time);
            int reqAdd = atWillUpdataMapper.addForm(map);
            if (reqAdd < 0) {
                throw new BussinessException(BizExceptionEnum.ADD_ERROR);
            }
        }
        //2 修改用户收益
        UserMoney userMoney = new UserMoney();
        userMoney.setUser_id(user_id);
        userMoney.setOwner_estimate(owner_estimate);
        userMoney.setAccumulated(accumulated);
        userMoney.setActivity_accumulated(activity_accumulated);
        userMoney.setFans_estimate(fans_estimate);
        userMoney.setBounty_accumulated(bounty_accumulated);
        userMoney.setDirect_fans(direct_fans);
        userMoney.setIndirect_fans(indirect_fans);
        int reqUpdataMoney = atWillUpdataMapper.updataUserProfile(userMoney);
        if (reqUpdataMoney < 0) {
            throw new BussinessException(BizExceptionEnum.UPDATE_ERROR);
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }


    /**
     * 查询 order 订单
     **/
    public Tip selectOrder(Order order) {
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }

    /**
     * 新增测试订单
     */
    public Tip addOrder(Order order) {
        if (null == order) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        order.setProduct_id("-1");
        order.setProduct_pic_url("测试");
        order.setProduct_name("测试商品");
        order.setChannel_id("测试渠道");
        order.setOrder_id("测试订单");
        order.setType(-1);
        order.setStatus(2);
        order.setClear_time("");
        order.setNumber(1);
        order.setActual_amount("100");
        order.setUser_rake("100");
        order.setBuytype(0);
        order.setTaobao_sid("-1");
        order.setTaobao_rid("-1");
        order.setRedpacket(3);
        orderMapper.insert(order);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }


    /**
     * 查询 用户 自身 某天jz_day_form 表
     */
    public Tip getUserFomr(String user_id, String time) {
        Map map = new HashMap();
        map.put("user_id", user_id);
        map.put("time", time);
        Map reqMap = atWillUpdataMapper.getForm(map);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), reqMap);
    }

    /**
     * 查询 用户 自身 某天jz_day_form 表
     */
    public Tip updataFomr(String id, String user_id, String time, Double estimate_commission, Double estimate_bounty, Double estimate_fans) {
        if (StringUtils.isEmpty(user_id)) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        Map map = new HashMap();
        map.put("id", id);
        map.put("user_id", user_id);
        map.put("time", time);
        map.put("estimate_commission", estimate_commission);
        map.put("estimate_bounty", estimate_bounty);
        map.put("estimate_fans", estimate_fans);
        if (StringUtils.isEmpty(id)) {
            //新增
            int req = atWillUpdataMapper.addForm(map);
            if (req < 1) {
                throw new BussinessException(BizExceptionEnum.ADD_ERROR);
            }
        } else {
            //修改
            int req = atWillUpdataMapper.updateFormTime(map);
            if (req < 1) {
                throw new BussinessException(BizExceptionEnum.UPDATE_ERROR);
            }
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }


    /**
     * 新增 或修改某用户 粉丝礼包订单发返佣
     **/
    public Tip addAndUpdataOrderGiftRake(String id, String user_id, Double user_rake_back) {
        Map map = new HashMap();
        map.put("id", id);
        map.put("user_id", user_id);
        map.put("user_rake_back", user_rake_back);
        if (StringUtils.isEmpty(id)) {
            //新增
            int req = atWillUpdataMapper.addOrderGiftRake(map);
            if (req < 1) {
                throw new BussinessException(BizExceptionEnum.ADD_ERROR);
            }
        } else {
            //修改
            int req = atWillUpdataMapper.updataOrderGiftRake(map);
            if (req < 1) {
                throw new BussinessException(BizExceptionEnum.UPDATE_ERROR);
            }
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }

    /**
     * 新增 或修改某用户 普通订单
     **/
    public Tip addAndUpdataOrder(String id, String user_id, Double user_rake_back_yugu) {
        Map map = new HashMap();
        map.put("id", id);
        map.put("user_id", user_id);
        map.put("user_rake_back_yugu", user_rake_back_yugu);
        if (StringUtils.isEmpty(id)) {
            //新增
            int req = atWillUpdataMapper.addOrder(map);
            if (req < 1) {
                throw new BussinessException(BizExceptionEnum.ADD_ERROR);
            }
        } else {
            //修改
            int req = atWillUpdataMapper.updataOrder(map);
            if (req < 1) {
                throw new BussinessException(BizExceptionEnum.UPDATE_ERROR);
            }
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }

    /**
     * 查询今日预估佣金 提示：获取今日最近的订单
     */
    public Tip getOrderMoney(String user_id) {
        Map map = atWillUpdataMapper.getOrderMoney(Integer.parseInt(user_id));
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), map);
    }

    /**
     * 查询今日预估奖励 提示：获取今日最近的订单 粉丝礼包订单返佣
     */
    public Tip getOrderGiftRakeMoney(String user_id) {
        Map map = atWillUpdataMapper.getOrderGiftRakeMoney(Integer.parseInt(user_id));
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), map);
    }
}
